/*
	Copyright 2008 CATsoft Development GmbH

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
/*
	Main Functions
*/
var detailsView;
var itemHeight = 20;
var clickedItem;
var todayOnTop;
var Connected = true;
var locations = new Array();

/***********************************************************************
 NOTES
- Adjust Manifest manually for using notifications
***********************************************************************/


/***********************************************************************
 Initalize Application
***********************************************************************/
function Init() {
	var token;

    pluginHelper.SetFlags( 0, gddContentFlagManualLayout);
	pluginHelper.onAddCustomMenuItems = onAddCustomMenuItems;

	options.putDefaultValue("showtags", "0" );

	todayOnTop = (options.getValue("todayOnTop") == "1" );

	// Initialize COMM
	COMM = new comm();

	// initalize RTM
	RTM = new rtm();
	//COMM.testConnection(null);

	RTM.setSecure( (options.getValue("securehttp") == "1" ));
	RTM.setToken( options.getValue("token") );
	
		if(COMM.connected){
			init2();
		} else {
			COMM.testConnection(init2);
		}
	}

function init2(){
		RTM.checkToken();
	token = RTM.getTokenValue();

	if(token.lenght == 0 ){
		info.innerText = NOT_AUTHORIZED;		
		info.visible = true;
	}
	else
	{
		if( token.length == 0 ){
			info.innerText = AUTH_ERROR2;	
			info.visible = true;
		}
		else{
			info.visible = false;
			smartDiv.visible = true;
			if(COMM.connected){
				getLists();
			} else {
				COMM.testConnection(getLists);
			}
		}
	}
	view.setTimeout( "checkUpdate(false)", 10000);		// delay 10 seconds for new version check
}

function getLists(){

	RTM.getLists(  );
	if(COMM.connected){
			getDateTimeformat();
		} else {
			COMM.testConnection(getDateTimeformat);
		}
}

function getDateTimeformat(){
	usDate = RTM.getDateformat();
			Time24 = RTM.getTimeformat();
			updateTasks(false);
}

/***********************************************************************
 Gadget moved to sidebar
***********************************************************************/
function view_ondock(){
	docked = true;
	
	view_onsize();
}

/***********************************************************************
 Gadeget moved from sidebar
***********************************************************************/
function view_onundock(){
	docked = false;
	
	view_onsize();
}

/***********************************************************************
 Update Taks
***********************************************************************/
function updateTasks( delay ) {
    if (delay) {
        if (timeout != -1)
            clearTimeout(timeout);
        timeout = view.setTimeout("updateTasks(false)", 20 * 1000); // Delay for 20 seconds
    }
    else {
        // Check if connection is available

        if(COMM.connected){
					updateTasks2();
				} else {
					COMM.testConnection(updateTasks2);

					info.innerText = HEADER_NOCONN;
					info.bold = true;
					header1.color = "#CC0000";

					if (timeout != -1)
						clearTimeout(timeout);

					timeout = view.setTimeout("updateTasks(false)", 5 * 60 * 1000); // Every 5 Minutes

				}

				
    }
}

function updateTasks2(){
	RTM.checkToken();
	if (RTM.isConnected()) {
		info.bold = false;
		if(COMM.connected){
			updateTasks3();
		} else {
			COMM.testConnection(updateTasks3);
		}
	}
	else {
			info.innerText = HEADER_NOCONN;
			info.bold = true;
			smartSave.enabled = false;
			header1.color = "#CC0000";
	}
	if (timeout != -1)
			clearTimeout(timeout);

	timeout = view.setTimeout("updateTasks(false)", 5 * 60 * 1000); // Every 5 Minutes
}

function updateTasks3(){
	RTM.getTasks(lists);
	showTasks();
	smartDiv.visible = true;
	saveLabel.visible = false;
	smartSave.enabled = true;
	header1.color = "#00CC00";
}

/***********************************************************************
 Clearing Remindes
***********************************************************************/
function clearReminders(){
	for(i=0; i < tasks.length; i++){
		if( tasks[i].timeoutToken != -1 )
		{
			clearTimeout( tasks[i].timeoutToken);
			tasks[i].timeoutToken = -1;
		}
	}
}

/***********************************************************************
 Show alert
***********************************************************************/
function showAlert( task ){
	var a;
	a = DUE_TEXT + " " + hourminutes(task.due) ;
	if (task.note != null)
		a = a + "\n\n" + task.note;
	var item = new ContentItem();
	item.heading = task.name;
	item.snippet = a;
	try{
		plugin.AddContentItem( item, gddItemDisplayAsNotification);
	}
	catch(e)
	{
		alert( task.name + "\n" + a );
	}
}

/***********************************************************************
	SetReminder
***********************************************************************/
function setReminder( i ){

	if( tasks[i].timeoutToken != -1)
	{
		clearTimeout( tasks[i].timeoutToken);
		tasks[i].timeoutToken = -1
		showAlert( tasks[i] );
	}
	
}

/***********************************************************************
	On Options Changed 
***********************************************************************/
function view_onOptionsChanged() {
	var token;

	if(inEdit)
		return;

	if( options.getValue( "optionsSaved") != 1 )
		return;

	token = options.getValue( "token" );
	RTM.setToken( token );
	todayOnTop = (options.getValue("todayontop") == "1" );
	secureHttp = (options.getValue("securehttp") == "1" );
	if( token.length == 0 ) {
		info.innerText = AUTH_ERROR;
		info.visible = true;
	}
	else {
		
		if(COMM.connected){
			view_onOptionsChanged2();
		} else {
			COMM.testConnection(view_onOptionsChanged2);
		}
	}
}

function view_onOptionsChanged2(){
	RTM.checkToken();
	token = RTM.getTokenValue();
	if( token.length == 0 ) {
			info.innerText = AUTH_ERROR;
			info.visible = true;
		}
		else {
			clearReminders();
			if(COMM.connected){
				getLists();
			} else {
				COMM.testConnection(getLists);
			}
		}
}


/***********************************************************************
	Show info for task as html view
***********************************************************************/
function showTaskInfo(i) {
  
	var info = "<html><body>" + tasks[i].due.toLocaleString() + " " + tasks[i].name + "<br/>" + tasks[i].note + "</body></html>";

  // Create the details view and set its content.
  detailsView = new DetailsView();
	detailsView.html_content = true;
	detailsView.setContent("", undefined, info, false, 0);

  // Show the details view  
  plugin.ShowDetailsView(detailsView,  // The DetailsView object
	  "Details",
	  gddDetailsViewFlagNone,  // Flags
	  closeDetailsView);  // The handler to call when details view closes
}


/***********************************************************************
	Close HTML Detail view
***********************************************************************/
function closeDetailsView() {
  plugin.CloseDetailsView();
}

/***********************************************************************
	Open Details view to edit task
***********************************************************************/
function openTask( task ){
	var token = RTM.getTokenValue();

	if( token == "" )	
		return;

	inEdit = true;

	detailsView = new DetailsView();
  detailsView.SetContent( "", undefined,  "edittask.xml",  false, 0 );
  detailsView.detailsViewData.putValue( "closeDetailsView", closeEditView);
	detailsView.detailsViewData.putValue( "currenttask", task );
	detailsView.detailsViewData.putValue("token", token);

	if( task > -1 )
	{
		detailsView.detailsViewData.putValue( "taskid", tasks[ task].id );
		detailsView.detailsViewData.putValue("taskname", tasks[ task].name);
		detailsView.detailsViewData.putValue( "tasklist", tasks[ task].listid );
		detailsView.detailsViewData.putValue( "taskprio", tasks[ task].priority );
		detailsView.detailsViewData.putValue("taskdue", formatDate( tasks[ task].due, tasks[task].has_due_time ));
		detailsView.detailsViewData.putValue("taskrepeat", tasks[ task].repeat);
		detailsView.detailsViewData.putValue("taskestimate", tasks[ task].estimate);
		detailsView.detailsViewData.putValue("tasktags", tasks[ task].tags);
		detailsView.detailsViewData.putValue( "tasklocation", tasks[ task].location );
		detailsView.detailsViewData.putValue("taskurl", tasks[ task].url);
	}

  plugin.ShowDetailsView(detailsView,  "",  gddDetailsViewFlagNone, onEditViewFeedback);  

}

/***********************************************************************
	Close a details view
***********************************************************************/
function  closeEditView() {
	inEdit = false;
  plugin.CloseDetailsView();
}

/***********************************************************************
	return from edit view
***********************************************************************/
var taskData;
var taskItem;

function onEditViewFeedback(detailsViewFlags) {
	taskData = new Object();

	if(detailsView.detailsViewData.getValue("saveTask" ) != "1" )
		return;
	
	task = detailsView.detailsViewData.getValue("currenttask");
	taskData.listid  =  detailsView.detailsViewData.getValue("tasklist");

	if(task >= 0)
		if(taskData.listid != tasks[task].listid)		// List moved
		{
			RTM.moveTask( task, taskData.listid)
			tasks[task].listid = taskData.listid;
		}

	taskData.name = encode_utf8( detailsView.detailsViewData.getValue("taskname") );
	taskData.priority  =  detailsView.detailsViewData.getValue("taskpriority");
	taskData.due  =  detailsView.detailsViewData.getValue("taskdue");
	taskData.repeat =  detailsView.detailsViewData.getValue("taskrepeat");
	taskData.estimate =  detailsView.detailsViewData.getValue("taskestimate");
	taskData.tags  =  detailsView.detailsViewData.getValue("tasktags");
	taskData.location  =  detailsView.detailsViewData.getValue("tasklocation");
	taskData.url  = detailsView.detailsViewData.getValue("taskurl");
	taskData.Id = detailsView.detailsViewData.getValue("taskid");

	if( task == -1 ){					// Create new entry
		if(COMM.connected){
				addTask();
			} else {
				COMM.testConnection(addTask);
			}
	}
	else{
		taskItem = tasks[ task ];

		if(COMM.connected){
			updateTask();
		} else {
			COMM.testConnection(updateTask);
		}
	}
}

function addTask(){
	taskItem = RTM.addTask( taskData );
	if(COMM.connected){
		updateTask();
	} else {
		COMM.testConnection(updateTask);
	}
}

function updateTask(){
	if( taskItem != null)
			RTM.updateTask( taskData, taskItem.id, taskItem.seriesid, taskItem.listid);

		inEdit = false;
		updateTasks(true);
}

/***********************************************************************
	Open Detail view ( menu)
***********************************************************************/
function openDetails( task, smartList) {
  detailsView = new DetailsView();
  
  detailsView.SetContent( "", undefined,  "details.xml",  false, 0 );
  detailsView.detailsViewData.putValue( "closeDetailsView", closeDetailsView);
  detailsView.detailsViewData.putValue( "task", task );
  detailsView.detailsViewData.putValue( "smartlist", smartList)
  plugin.ShowDetailsView(detailsView,  "",  gddDetailsViewFlagNone, onDetailsViewFeedback);  
}

/***********************************************************************
	Close details view
***********************************************************************/
function closeDetailsView() {
  plugin.CloseDetailsView();
}

/***********************************************************************
	return from details view
***********************************************************************/
var task;
function onDetailsViewFeedback(detailsViewFlags) {
	task = detailsView.detailsViewData.getValue("task");
	var action = detailsView.detailsViewData.getValue("action");
	var smartList = detailsView.detailsViewData.getValue("smartList");

	switch(action){
		case 'edit':
			openTask( task );
			break;
		case 'complete':
				if(COMM.connected){
					fixIt();
				} else {
					COMM.testConnection(fixIt);
				}
			break;
	    case 'postpone':
				if(COMM.connected){
					postpone();
				} else {
					COMM.testConnection(postpone);
				}
			break;
	}
}

function fixIt(){
	RTM.fixIt( task );
	updateTasks(true);
}

function postpone(){
	RTM.postPone( task );
	updateTasks(true);
}

/***********************************************************************
	Doubleclick on Task
***********************************************************************/
function openTaskInBrowser( task ){
	OpenURL( "http://www.rememberthemilk.com/home/" + RTM.getUsername() + "/" + tasks[ task ].listid + "/" + tasks[ task ].id )
}

/***********************************************************************
	Click on task
***********************************************************************/
function mainClick( task, smartList )
{
if( event.x < 14)
	openDetails( task, smartList );
}

/***********************************************************************
	SmartAdd a new Task: Save with Enter
***********************************************************************/
function smartAddTaskKeyboard(){
	if(event.keyCode == 13)
		smartAddTask();
	else
		event.returnValue = true;
}

/***********************************************************************
	SmartAdd a new Task
***********************************************************************/
var smartTaskData;
var smartTaskItem;
var intervalTimer;

function smartAddTask(){
	smartDiv.visible = false;
	saveLabel.visible = true;
	view.setTimeout(smartAddTask1, 1000);
}

function smartAddTask1(){

if(COMM.connected){
		RTM.addSmartTask( lists[0].id, smartTask.value);

			saveLabel.visible = false;
			smartTask.value ="";
			smartDiv.visible = true;
	} else {
		COMM.testConnection(smartAddTask1);
	}

/*
//	smartSave.enabled = false;

	taskString = smartTask.value;
//	smartTask.enabled = false;


	smartTaskData = new Object();
	smartTaskData.listid = lists[0].id;
	smartTaskData.name = "";
	smartTaskData.priority  =  "";
	smartTaskData.due  =  "";
	smartTaskData.repeat =  "";
	smartTaskData.estimate =  "";
	smartTaskData.tags  =  "";
	smartTaskData.location  =  "";
	smartTaskData.url  = "";
	smartTaskData.Id = "";

	if(COMM.connected){
		RTM.onAddViewFeedback(detailsViewFlags) ();
	} else {
		COMM.testConnection(parseSmartInputString);
	}
*/
}

function parseSmartInputString() {
	
	RTM.getLists();
	RTM.getLocations();
	
	var strList = taskString.split(" ");
	var tmpString = "";
	for(var i = strList.length - 1; i >= 0; i--){
		if(strList[i].search(/^=/) != -1){ // Time Estimate
			tmpString = concatSmartStrings(strList[i].substring(1), tmpString);
			smartTaskData.estimate = tmpString;
			tmpString = "";

		} else if(strList[i].search(/^\*/) != -1){ // Repeat
			tmpString = concatSmartStrings(strList[i].substring(1), tmpString);
			smartTaskData.repeat = tmpString;
			tmpString = "";

		} else if(strList[i].search(/^@/) != -1){ // Location
			tmpString = concatSmartStrings(strList[i].substring(1), tmpString);
			for(var j = 0; j < locations.length; j++){
				if(locations[j].name == tmpString){
					smartTaskData.location = locations[j].id;
					break;
				}
			}
			tmpString = "";

		} else if(strList[i].search(/^#/) != -1){ // List
			tmpString = concatSmartStrings(strList[i].substring(1), tmpString);
			for(var j = 0; j < lists.length; j++){
				if(lists[j].name == tmpString){
					smartTaskData.listid = lists[j].id;
					break;
				}
			}
			tmpString = "";

		} else if(strList[i].search(/^!/) != -1){ // Priority
			tmpString = concatSmartStrings(strList[i].substring(1), tmpString);
			smartTaskData.priority = tmpString;
			tmpString = "";

		} else if(strList[i].search(/^\^/) != -1){ // Due Date
			tmpString = concatSmartStrings(strList[i].substring(1), tmpString);
			smartTaskData.due = tmpString;
			tmpString = "";

		} else { // no special signs in substring -> space has to be in string to save
			tmpString = concatSmartStrings(strList[i], tmpString);
		}
	}
	smartTaskData.name = tmpString;

	if(COMM.connected){
		smartAddTask2();
	} else {
		COMM.testConnection(smartAddTask2);
	}

	
}

function smartAddTask2(){
	smartTaskItem = RTM.addTask( smartTaskData );
	if(COMM.connected){
		smartAddTask3();
	} else {
		COMM.testConnection(smartAddTask3);
	}
}

function smartAddTask3(){
	if( smartTaskItem != null)
			RTM.updateTask( smartTaskData, smartTaskItem.id, smartTaskItem.seriesid, smartTaskItem.listid);

		updateTasks(true);

	view.clearInterval(intervalTimer);
	saveLabel.visible = false;
	smartTask.value = "";
	smartDiv.visible = true;
}

function concatSmartStrings(str1, str2){
	if(str2.length == 0)
		str2 = str1 ;
	else
		str2 = str1 + " " + str2;

	return str2;
}

/***********************************************************************
	Add Menu Item
***********************************************************************/
function onAddCustomMenuItems(menu) 
{
  menu.AddItem(UPDATE_CHECK, 0, runcheckupdate);

  if ((RTM.getTokenValue().length == 0) || (!RTM.isConnected())) {
      menu.AddItem(ADD_LIST, gddMenuItemFlagGrayed, runaddlist);
      menu.AddItem(REFRESH_TASKS, gddMenuItemFlagGrayed, runupdatetasks);
  }
  else {
      menu.AddItem(ADD_LIST, 0, runaddlist);
      menu.AddItem(REFRESH_TASKS, 0, runupdatetasks);
  }

  function runcheckupdate() { checkUpdate(true) }
  function runaddlist() { addList() }
  function runupdatetasks() { updateTasks(false) }
}

/***********************************************************************
 Add List
***********************************************************************/
function addList() {

    detailsView = new DetailsView();
    detailsView.SetContent( "", undefined,  "addlist.xml",  false, 0 );
		detailsView.detailsViewData.putValue( "closeAddView", closeAddView);
    plugin.ShowDetailsView(detailsView,  "",  gddDetailsViewFlagNone, onAddViewFeedback);  
}

/***********************************************************************
	return from add list view
***********************************************************************/
function onAddViewFeedback(detailsViewFlags) {
    var listName = detailsView.detailsViewData.getValue("listname");
    
    if(listName.length>0)
        RTM.addList(listName);
}

/***********************************************************************
return from version view
***********************************************************************/
function closeAddView() {
    plugin.CloseDetailsView();
}

/***********************************************************************
	return from version view
***********************************************************************/
function onVersionViewFeedback(detailsViewFlags) {
}

/***********************************************************************
	Check for new version
***********************************************************************/
function checkUpdate(manualrequest)
{
	var today = new Date();

	if( !manualrequest)
	{
		var lastcheck = options.getValue("lastcheck");
		if( lastcheck + 86400000 >  today.getTime())
				return;
	}
	else
		view.setTimeout( "checkUpdate(false)", 86400000);		// Come back one day later

	var version = '';
	if(framework.system.network.online){
		var parser = COMM.sendXMLHttpRequest( "http://www.catsoft.ch/gg/rtmversioninfo.xml", false );

		if (parser)
		{
			if( parser.checkError(false).length == 0 ) 
			{
				version = parser.getValue("version");
				
				if(version > GADGET_VERSION)
				{
					detailsView = new DetailsView();
			
					detailsView.SetContent(  "", undefined,  "newversion.xml",  false, 0 );
					detailsView.detailsViewData.putValue( "closeDetailsView", closeDetailsView);
					detailsView.detailsViewData.putValue( "version", version);
					detailsView.detailsViewData.putValue( "description", parser.getValue("description"));
					detailsView.detailsViewData.putValue( "link", parser.getValue("link"));
					plugin.ShowDetailsView(detailsView,  "",  gddDetailsViewFlagNone, onVersionViewFeedback);  
				}
					//if there is no update, and the user has manually asked tell them
				else if(manualrequest)
				{
					alert(CURRENT_VERSION);
				}

				options.putValue("lastcheck", today.getTime());
			}
		}
	}
}


